package com.foo.demo.web.servlet;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@WebServlet(name = "indexServlet", urlPatterns = {"/indexServlet", "/"})
public class IndexServlet extends HttpServlet {

    private Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    private static List<String> userNameList = new ArrayList<String>();

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        logger.info("entering doGet");
        resp.getWriter().println("Get:/indexServlet");
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        logger.info("entering doPost");
        String name = req.getParameter("name");
        req.setAttribute("name", name);
        int luckNumber = new Random(10).nextInt();
        req.setAttribute("luckNumber", luckNumber);
        userNameList.add(name);

        req.setAttribute("userNameList", userNameList);
        req.getRequestDispatcher("/pages/success.jsp").forward(req, resp);
    }
}
